<!--
 * @Description: 我的
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-04-10
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-04-18
-->
<script lang="ts" setup>
  import { computed, onMounted, ref } from 'vue'

  import checkboxCheck from '@/assets/checkbox-check.png'
  import checkboxUnCheck from '@/assets/checkbox-uncheck.png'
  import radioCheck from '@/assets/radio-check.png'
  import radioUnCheck from '@/assets/radio-uncheck.png'
  import rightArrow from '@/assets/right-arrow.png'
  import BottomButton from '@/components/BottomButton/BottomButton.vue'
  import { HttpCodeEnum } from '@/enum/httpEnum'
  import { questionTypeDesc } from '@/enum/questionEnum'
  import { scanTypeDesc } from '@/enum/statusResultsEnum'
  import env from '@/env/index'
  import type { ICmsOption, ICmsPickerOption, ICmsQuestion } from '@/plugin/cmsAnalysis'
  import { CmsQuestionTypeEnum, CmsResStatusEnum, useCmsAnalysis } from '@/plugin/cmsAnalysis'
  import { useUserInfoStore } from '@/stores/userInfo'
  import { getUserId } from '@/utils/storage'
  import { getToken } from '@/utils/storage'
  import { deleteArrayItem, delHtmlTag } from '@/utils/util'

  import Layout from './components/Layout.vue'
  import Progress from './components/Progress.vue'
  const userInfoStore = useUserInfoStore()
  const props = defineProps<{ publishId: string; detectionInfoId: string; questionnaireRecordId: string }>()
  const param_publishID = props.publishId // '763F0D62F0024E81A6A4EC4F4FFBBEC6' 995F146029FE4EC2840B2E59620FADE9
  const isScroll = ref(false) // 非必填

  const { paper, preparePaper, analysisPaperTemplate, createOnePaper, submitPaper } = useCmsAnalysis()
  onMounted(async () => {
    preparePaper({
      publishId: param_publishID,
      userId: getUserId(),
      nickname: userInfoStore.userName || '',
      detectionInfoId: props.detectionInfoId,
      detectionType: userInfoStore.detectionType,
    })
    await analysisPaperTemplate()
    await createOnePaper()
  })
  //当前题目索引
  const currentIndex = ref(0)

  //答题列表
  const answerList = ref([0])

  //是否需要校验规则提示
  const isRule = ref(false)
  const isRuleTip = ref(false)

  //当前题目
  const currentQuestion = computed(() => {
    return paper.value?.questions[currentIndex.value]
  })

  const nextText = computed(() => {
    let text = '下一题'
    if (currentQuestion.value.answer.targetId === -1) text = '提交'
    if (currentIndex.value === paper.value.questions.length - 1) text = '提交'
    return text
  })
  /**上一题 */
  const prev = () => {
    if (currentIndex.value === 0) return
    answerList.value = deleteArrayItem(answerList.value, currentIndex.value)
    currentIndex.value = answerList.value[answerList.value.length - 1]
  }
  /**
   * 下一步：交卷
   */
  const next = async () => {
    if (!currentQuestion.value) return
    if ((currentQuestion.value.required || isRuleTip.value) && !currentQuestion.value.answer.isAnswer) {
      return
    }
    if (currentQuestion.value.questionType === CmsQuestionTypeEnum.RADIO) {
      if (currentQuestion.value.answer.targetId && currentQuestion.value.answer.targetId > 0) {
        currentIndex.value = paper.value.questions.findIndex((item) => item.questionId === currentQuestion.value.answer.targetId)
        answerList.value.push(currentIndex.value)
        return
      } else if (currentQuestion.value.answer.targetId === -1) {
        submit()
        return
      }
    }
    if (currentIndex.value === paper.value.questions.length - 1) {
      submit()
      return
    }
    currentIndex.value = currentIndex.value + 1
    answerList.value.push(currentIndex.value)
    isRuleTip.value = false
    isRule.value = false
  }
  const submit = async () => {
    const { status, message } = await submitPaper()
    console.log('submitPaper: ', status)
    if (status === CmsResStatusEnum.SUCCESS) {
      if (userInfoStore.detectionType === 1) {
        uni.redirectTo({
          url: `/pages/detection/collectSamples?detectionInfoId=${props.detectionInfoId}`,
        })
        return
      }
      uni.redirectTo({
        url: `/pages/detection/position?detectionInfoId=${props.detectionInfoId}`,
      })
    } else {
      uni.showToast({ title: message, icon: 'none' })
    }
  }

  /**
   * 选中单选选项
   * @param question 问题
   * @param option 问题选项
   */
  const checkRadio = (question: ICmsQuestion, option: ICmsOption) => {
    question.answer.radio = option.optionId
    question.answer.targetId = option.targetId
    question.answer.isAnswer = true
  }

  /**
   * 选中多选选项
   * @param question 问题
   * @param option 问题选项
   */
  const checkCheckbox = (question: ICmsQuestion, option: ICmsOption) => {
    if (question.answer.checkbox?.includes(option.optionId)) {
      question.answer.checkbox = deleteArrayItem(question.answer.checkbox, option.optionId)
    } else {
      question.answer.checkbox.push(option.optionId)
    }
    question.answer.isAnswer = true
  }

  /** picker切换选项 */
  const onPickerChange = (e: WechatMiniprogram.PickerChange, question: ICmsQuestion) => {
    const options = (question.options[0]?.optionText ?? []) as ICmsPickerOption[]
    const index = parseInt(e.detail.value as string)
    question.answer.picker = options[index].value
    question.answer.isAnswer = true
  }

  /** picker选项内容 */
  const getPickerRanges = computed(() => {
    return (question: ICmsQuestion) => question.options[0]?.optionText ?? []
  })

  /** picker选中项-索引 */
  const getPickerIndex = computed(() => {
    return (question: ICmsQuestion) => {
      const options = (question.options[0]?.optionText ?? []) as ICmsPickerOption[]
      return options.findIndex((item) => item.value === question.answer.picker)
    }
  })

  /** picker选中项-回显文本 */
  const getPickerText = computed(() => {
    return (question: ICmsQuestion) => {
      const options = (question.options[0]?.optionText ?? []) as ICmsPickerOption[]
      return options.find((item) => item.value === question.answer.picker)?.label
    }
  })

  const previewFile = (question: any) => {
    wx.openDocument({
      filePath: question.answer.fileData.path, // 服务器路径预览需先下载，所以用本地路径预览
      fail: function (err) {
        console.log('打开文档失败： ', err)
        console.log('filePath： ', question.answer.fileData.path)
        uni.showToast({ title: err.errMsg, icon: 'none', duration: 4000 })
      },
    })
  }
  const uploadFile = (question: any, res: any) => {
    // question.answer.file 文件服务器地址 uploadFile成功之后返回
    // question.answer.fileData 文件信息
    question.answer.fileData = res.tempFiles[0]
    wx.showLoading({
      title: '文件上传中',
    })
    wx.uploadFile({
      url: `${env.api}/contentFile/upload/V1`,
      filePath: question.answer.fileData.path, // 文件本地路径
      name: 'file',
      header: { Authorization: getToken() },
      async success(res: any) {
        const data = JSON.parse(res.data)
        console.log('uploadFile success: ', res)
        if (data.responseCode === HttpCodeEnum.SUCCESS) {
          question.answer.file = data.responseData
          console.log('responseData: ', question.answer.file)
          question.answer.isAnswer = true
        } else {
          uni.showToast({ title: data.responseMessage || '文件上传失败', icon: 'none' })
          question.answer.isAnswer = false
        }
      },
      fail(err) {
        console.log('uploadFile fail: ', err)
        uni.showToast({ title: err.errMsg || '文件上传失败', icon: 'none' })
        question.answer.isAnswer = false
      },
      complete() {
        wx.hideLoading()
      },
    })
  }

  /**文本输入框输入监听 */
  const onInput = (value: any) => {
    if (!value.detail.value && !currentQuestion.value.required) {
      isRule.value = false
      isRuleTip.value = false
      return
    }
    const regexRule = paper.value.questions[currentIndex.value].options[0].regexRule
    if (!regexRule) {
      paper.value.questions[currentIndex.value].answer.isAnswer = value.detail.value ? true : false
      return
    }
    paper.value.questions[currentIndex.value].answer.isAnswer = new RegExp(regexRule).test(value.detail.value) ? true : false
    isRuleTip.value = !paper.value.questions[currentIndex.value].answer.isAnswer
  }

  const clearFileData = (question: any) => {
    question.answer.file = ''
    question.answer.fileData = {}
    question.answer.isAnswer = false
  }
  //监听光标
  const onfocus = (value: any) => {
    isScroll.value = false
    console.log('onfocus: ', isScroll.value)
  }
  //监听失去焦点
  const onblur = (value: any) => {
    isScroll.value = true
    isRule.value = !paper.value.questions[currentIndex.value].answer.isAnswer
  }
  const selectFile = (question: any, count: number) => {
    wx.chooseMessageFile({
      count: count,
      type: 'all',
      success(res) {
        console.log('chooseMessageFile: ', res)
        clearFileData(question)
        uploadFile(question, res)
      },
      fail(err) {
        console.log('chooseMessageFile err: ', err)
        clearFileData(question)
      },
    })
  }
</script>

<template>
  <Layout :title="scanTypeDesc[userInfoStore.detectionType]" :is-scroll="true">
    <template #progress> <Progress step="1" :type="userInfoStore.detectionType" name="填写问卷" /></template>
    <template #content v-if="paper.questions">
      <!-- <view class="paper"> -->
      <!-- <view class="paper-title">问卷：{{ paper.paperName }}</view> -->
      <view class="paper-questions">
        <view class="paper-question">
          <view class="paper-question-title title-number">
            <text class="paper-question-title-checkbox">{{ questionTypeDesc[paper.questions[currentIndex].questionType] }}</text>
            第{{ currentIndex + 1 }}题
          </view>
          <view class="paper-question-title">
            <text class="paper-question-required" v-if="currentQuestion.required">*</text>
            <text class="question-title">{{ delHtmlTag(currentQuestion.questionName) }}</text>
          </view>
          <view class="paper-question-content">
            <!-- 填空 -->
            <input
              class="input"
              type="text"
              v-if="currentQuestion.questionType === CmsQuestionTypeEnum.INPUT"
              v-model="currentQuestion.answer.input"
              @focus="onfocus"
              @blur="onblur"
              @input="onInput"
            />

            <!-- 单选 -->
            <view class="radio" v-else-if="currentQuestion.questionType === CmsQuestionTypeEnum.RADIO">
              <view
                class="radio-item"
                v-for="(option, optionI) in currentQuestion.options"
                :key="`radio-item${optionI}`"
                @click="checkRadio(currentQuestion, option)"
                :class="{ 'item-checked': currentQuestion.answer.radio === option.optionId }"
              >
                <image class="icon" :src="currentQuestion.answer.radio === option.optionId ? radioCheck : radioUnCheck" />
                <text class="text" :class="{ 'text-checked': currentQuestion.answer.radio === option.optionId }">{{ option.optionText }}</text>
                <!-- <view class="division-line-solid" /> -->
              </view>
            </view>
            <!-- 多选 -->
            <view class="checkbox" v-else-if="currentQuestion.questionType === CmsQuestionTypeEnum.CHECKBOX">
              <view
                class="checkbox-item"
                v-for="(option, optionI) in currentQuestion.options"
                :key="`checkbox-item${optionI}`"
                @click="checkCheckbox(currentQuestion, option)"
                :class="{ 'item-checked': currentQuestion.answer.checkbox?.includes(option.optionId) }"
              >
                <image class="icon" :src="currentQuestion.answer.checkbox?.includes(option.optionId) ? checkboxCheck : checkboxUnCheck" />
                <text class="text" :class="{ 'text-checked': currentQuestion.answer.checkbox?.includes(option.optionId) }">{{ option.optionText }}</text>
              </view>
            </view>
            <!-- 列表选择 -->
            <view class="picker" v-else-if="currentQuestion.questionType === CmsQuestionTypeEnum.PICKER">
              <picker
                @change="onPickerChange($event, currentQuestion)"
                :value="getPickerIndex(currentQuestion)"
                :range="getPickerRanges(currentQuestion)"
                range-key="label"
              >
                <view class="FormSelect-select">
                  <text class="placeholder" v-if="isNaN(currentQuestion.answer.picker)">请选择</text>
                  <text class="name" v-else>{{ getPickerText(currentQuestion) }}</text>
                </view>
              </picker>
              <!-- <text class="right-arrow">></text> -->
              <image class="icon" mode="widthFix" :src="rightArrow" />
            </view>
            <!-- 文件上传 -->
            <view class="file" v-else-if="currentQuestion.questionType === CmsQuestionTypeEnum.FILE">
              <view class="select-file" @click="selectFile(currentQuestion,1)">选择文件</view>
              <template v-if="currentQuestion.answer.file && currentQuestion.answer?.fileData?.path">
                <view v-if="currentQuestion.answer?.fileData?.type === 'file'" class="flie-content">
                  <text @click="previewFile(currentQuestion)">{{ currentQuestion.answer?.fileData?.name }}</text>
                </view>
                <view v-else class="flie-content">
                  <image :src="currentQuestion.answer.file" mode="widthFix" />
                </view>
              </template>
            </view>
            <view class="message" v-if="isRule"
              >请输入正确的{{ currentQuestion.options[0].regexMsg ? currentQuestion.options[0].regexMsg : delHtmlTag(currentQuestion.questionName) }}</view
            >
          </view>
          <!-- <view class="division-line-dotted" /> -->
        </view>
      </view>
      <!-- </view> -->
    </template>
    <template #button v-if="paper.questions">
      <view class="btn_outer">
        <BottomButton buttonText="上一题" @on-click="prev()" class="btn" :isPre="true" :class="{ 'btn-disabled': currentIndex === 0 }" />
        <BottomButton
          :buttonText="nextText"
          @on-click="next()"
          class="btn"
          :isPre="false"
          :class="{ 'btn-disabled': (currentQuestion.required || isRule) && !paper.questions[currentIndex].answer.isAnswer }"
        />
      </view>
    </template>
  </Layout>
</template>

<style lang="less" scoped>
  :deep(.content) {
    margin-top: 48rpx !important;
  }

  .division-line-dotted {
    margin: 38rpx 0 40rpx;
    border-top: 2rpx dotted #e0e1e6;
  }

  .paper-questions {
    font-size: 28rpx;
    color: #1d2129;

    .paper-question {
      margin: 8rpx 0;

      .paper-question-title {
        margin-bottom: 35rpx;

        .paper-question-required {
          margin-right: 8rpx;
          color: #ff5d5d;
        }

        .paper-question-title-checkbox {
          width: 80rpx;
          height: 40rpx;
          padding: 10rpx 16rpx;
          margin-right: 8rpx;
          font-size: 24rpx;
          color: #00474f;
          background: #87e8de;
          border-radius: 4rpx;
        }
      }

      .question-title {
        font-size: 36rpx;
        font-weight: 600;
      }

      .title-number {
        color: #666;
      }

      .paper-question-content {
        .input {
          height: 88rpx;
          padding: 0 24rpx;
          background: #f7f8fa;
          border-radius: 4px;

          &:focus {
            background: #fff;
            border: 2rpx solid #13c2c2;
            border-radius: 4px;
            outline: none;
          }
        }

        .radio {
          .radio-item {
            display: flex;
            align-items: center;
            min-height: 88rpx;
            padding: 10px;

            &:not(:nth-last-of-type(1)) {
              border-bottom: 1px solid #f7f8fa;
            }

            .icon {
              width: 40rpx;
              height: 40rpx;
            }

            .text {
              flex: 1;
              margin-left: 12rpx;
            }
          }
        }

        .item-checked {
          background-color: #f8f8f8;
        }

        .text-checked {
          color: #13c2c2;
        }

        .checkbox {
          .checkbox-item {
            display: flex;
            align-items: center;
            min-height: 88rpx;

            &:not(:nth-last-of-type(1)) {
              border-bottom: 1px solid #f7f8fa;
            }

            .icon {
              flex-shrink: 0;
              width: 40rpx;
              height: 40rpx;
            }

            .text {
              padding: 48rpx 0;
              margin-left: 12rpx;
            }
          }
        }

        .picker {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 88rpx;
          padding: 0 24rpx;
          color: #86909c;
          background: #f7f8fa;
          border-radius: 4px;

          > picker {
            width: 100%;
          }

          .icon {
            width: 32rpx;
          }
        }

        .file {
          margin-top: 32rpx;

          .select-file {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 88rpx;
            font-size: 32rpx;
            font-weight: 500;
            color: #08979c;
            text-align: center;
            border: 1px solid #08979c;
            border-radius: 44rpx;
          }

          .flie-content {
            margin-top: 32rpx;

            image {
              width: 100%;
            }
          }
        }

        .message {
          margin-top: 5px;
          color: #ff5d5d;
        }
      }
    }
  }

  .btn_outer {
    display: flex;

    .btn {
      flex: 1;
    }

    .btn-disabled {
      opacity: 0.6;
    }
  }
</style>
